package alijk.dataView.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import alijk.dataView.model.RequestBean;
import alijk.dataView.utils.Constants;
import alijk.dataView.utils.JavaBeanUtils;
import alijk.dataView.utils.WeatherUtils;
import alijk.dataView.utils.ZolJokeParser;
/**
 * 微信消息处理
 * @time 2014年11月24日 上午10:22:07
 * @author CheWenliang
 */
public class HandleWeiXinMessageServlet extends HttpServlet{
	
	public static final Logger logger = LoggerFactory
			.getLogger(HandleWeiXinMessageServlet.class);
	/**
	 * VersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	/*
	 * URL验证
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        logger.info(signature + " -- " + timestamp + " -- " + nonce + " -- " + echostr);
        PrintWriter out = resp.getWriter();
        out.write(echostr);
    }
	/*
	 * 消息的回复 
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	 @Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	            throws ServletException, IOException {
		logger.info("有人发消息来了----");
		Scanner scanner = new Scanner(req.getInputStream());
        resp.setContentType("application/xml");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();
        RequestBean reqBean = null;
        try {
			StringBuffer buffer = new StringBuffer();
			while(scanner.hasNext()){
				buffer.append(scanner.next());
			}
			logger.info("消息头为："+buffer.toString());
			reqBean = JavaBeanUtils.converyToJavaBean(buffer.toString(), RequestBean.class);
			logger.info("请求头信息OBJ："+reqBean.getFromUserName()
					+"LAT:"+reqBean.getLocation_X()+"LNG:"+reqBean.getLocation_Y());
			
			String respContent = "";
			//如果是有人关注的话
			if(Constants.messageType_event.equals(reqBean.getMsgType())){
				respContent = WeatherUtils.getGuanZhuMessage();;
			}else if(reqBean.getLocation_X()!=null
					&&reqBean.getLocation_Y()!=null){//如果传入了地理位置
				//TODO 获取天气
				String city = WeatherUtils.getLocationCity(reqBean.getLocation_X().toString(), 
						reqBean.getLocation_Y().toString());
				String weather = WeatherUtils.getTemp(city);
				respContent = weather;
			}else{
				String content = reqBean.getContent();
				if(content.contains(Constants.qad)){
					respContent = Constants.qad_content;
				}else if(content.contains(Constants.sll)){
					respContent = Constants.sll_content;
				}else if(content.contains(Constants.lyf)){
					respContent = Constants.lyf_content;
				}else if(content.contains(Constants.cwl)){
					respContent = Constants.cwl_content;
				}else if(content.contains(Constants.tq)){
					String[] arr = content.split("@");
					if(arr.length < 2){
						respContent = "大哥or大姐,信息格式不对哦";
					}else{
						respContent = WeatherUtils.getTemp(arr[1]);
					}
				}else{
					//得一个joke
					respContent = ZolJokeParser.getOneJoke();
				}
			}
			
			logger.info("get joke:"+respContent);
			out.write(JavaBeanUtils.getResponseXml(reqBean, respContent));
			out.flush();
		} catch (Exception e) {
			logger.error(e.getMessage());
			out.write(JavaBeanUtils.getResponseXml(reqBean, "亲,服务器泡妞去了,请重新发送消息!"));
			out.flush();
		} finally{
			if (scanner != null) {
                scanner.close();
                scanner = null;
            }
            if (out != null) {
                out.close();
                out = null;
            }
		}
	}
}
